﻿/*
	Class				SearchBox
	
	Description		Input area for searches. It handles taking keyboard input, and rendering the Pixelized text.
					
	History			1.00		7/14/07		Created
	
	To Do				------
*/

package tv.digitalfx
{
	import tv.digitalfx.DisplayType;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.*;
	
	public class SearchBox extends DisplayType
	{
		private const DEFAULT:String		= "SEARCH";
		private const CARET:String		= "\u00a6";
		
		
		public function SearchBox ($font:Font, $color:uint)
		{
			super 					($font, $color);
			textField.type				= TextFieldType.INPUT;
			textField.restrict			= "A-Za-z0-9" + CARET;
			textField.addEventListener	(TextEvent.TEXT_INPUT, beforeInput);
			textField.addEventListener	(Event.CHANGE, onInput);
			textField.addEventListener	(KeyboardEvent.KEY_DOWN, specialKeysInput);
			defaultText ();
		}
		
		
		
		public function defaultText ():void
		{
			text						= DEFAULT;
		}
		
		
		
		public function clearText ():void
		{
			text						= CARET;
		}
		
		
		
		private function beforeInput ($event:Event):void
		{
			if (text == DEFAULT)
			{
				clearText ();
			}
		}
		
		
		
		private function onInput ($event:Event):void
		{
			removeCustomCaret ();
			addCustomCaret ();
		}
		
		
		
		private function specialKeysInput ($event:KeyboardEvent):void
		{
			if ($event.keyCode == 13 || $event.keyCode == 9) // Return or Tab
			{
				removeCustomCaret ();
				trace				("Go to: " + textField.text);
				defaultText ();
			}
			
			
			else if ($event.keyCode == 27) // Esc
			{
				defaultText ();
			}
		}
		
		
		
		private function removeCustomCaret ():void
		{
			if (text.search (CARET) >= 0) // If caret is there, remove it
			{
				var substrings:Array	= textField.text.split (CARET);
				text					= substrings[0] + substrings[1];
			}
		}
		
		
		
		private function addCustomCaret ():void
		{
			var caretIndex:int			= textField.caretIndex;
			var beforeCaret:String		= textField.text.substring (0, caretIndex);
			var afterCaret:String		= textField.text.substring (caretIndex);
			
			text						= beforeCaret + CARET + afterCaret;
		}
			
		
	}
}